package com.vecspace.core.support;

import java.io.File;
import java.lang.annotation.Annotation;
import java.util.Map;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.support.AbstractApplicationContext;

import com.vecspace.utils.log.HLogger;

public class BeansContextUtil implements ApplicationContextAware {

	private static ApplicationContext appContext;

	private BeansContextUtil(){
		//输出根路径的绝对路径
		File baseDir = new File("./");
		String msg = "path of File('./') -> :" + baseDir.getAbsolutePath();
		System.out.println(msg);
		HLogger.DEFAULT().info(msg);
		
		baseDir = new File("/");
		msg = "path of File('/') -> :" + baseDir.getAbsolutePath();
		System.out.println(msg);
		HLogger.DEFAULT().info(msg);
	}

	@Override
	public void setApplicationContext(
			ApplicationContext arg0)
			throws BeansException {
		BeansContextUtil.appContext = (AbstractApplicationContext) arg0;
		if(null == BeansContextUtil.appContext ){
			HLogger.DEFAULT().info("注入 spring ApplicationContext异常");
		}else{
			HLogger.DEFAULT().info("注入 spring ApplicationContext成功");
		}
		
	}

	public static ApplicationContext getApplicationContext() {		
		return BeansContextUtil.appContext;
	}

	@SuppressWarnings("unchecked")
	public static <T> T getBean(String beanName) {
		ApplicationContext ctx = BeansContextUtil.getApplicationContext();
		Object bean = ctx.getBean(beanName);
		return (T)bean;
	}
	
	public static Map<String, Object> getBeansWithAnnotation(Class<? extends Annotation> annoType){
		ApplicationContext ctx = BeansContextUtil.getApplicationContext();
		Map<String, Object> beans = ctx.getBeansWithAnnotation(annoType);		
		return beans;
	}
	
	public static void main(String [] args) {
		System.out.println(BeansContextUtil.getApplicationContext());
		System.out.println(BeansContextUtil.getBean("bookService").getClass().getName());
	}
	
}